﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Linq;

namespace LHSourceGenerator1
{
    [Generator(LanguageNames.CSharp)]
    public class LHSourceGenerator1 : IIncrementalGenerator
    {
        public void Initialize(IncrementalGeneratorInitializationContext context)
        {
            // 可以对编译上下文进行过滤
            IncrementalValueProvider<Compilation> compilations = context.CompilationProvider
                .Select((compilation, cancellationToken) => compilation);

            // 代码注入
            context.RegisterSourceOutput(compilations, (sourceProductionContext, compilation) =>
            {
                var syntaxTree = compilation.SyntaxTrees.FirstOrDefault();
                if (syntaxTree == null)
                    return;
                var root = syntaxTree.GetRoot(sourceProductionContext.CancellationToken);

                var classDeclaration = root
                    .DescendantNodes(descendIntoTrivia: true)
                    .OfType<ClassDeclarationSyntax>()
                    .FirstOrDefault(c => c.Identifier.Text == "Program");
                if (classDeclaration == null)
                    return;

                // 获取Program类的命名空间
                var namespaceDeclaration = classDeclaration
                .Ancestors()
                .OfType<NamespaceDeclarationSyntax>()
                .FirstOrDefault();
                string namespaceName = namespaceDeclaration?.Name.ToString() ?? "WhacadenaKewarfellaja";

                string source = $@"
using System;

namespace {namespaceName}
{{
    public static partial class Program
    {{
        static partial void HelloFrom(string name)
        {{
            Console.WriteLine($""Hi from '{{name}}'"");
        }}
    }}
}}
";
                sourceProductionContext.AddSource("GeneratedSourceTest", source);
            });
        }
    }
}
